# coding = utf-8
import random
import pickle
import os


# 欢迎词
def say_hello():
    hello = '''
---------------------------------------------------------
             智障猜数字游戏               
 1，数字范围为1-50的整数，一轮最多尝试20次  
 2，输入用户名即可开始游戏。               
---------------------------------------------------------
    '''
    print(hello, end='')


# 读档
# 用户名 游戏次数     最快猜出轮数     猜过总轮数
# 张三   2         1（0表示没猜对过）    10
def read_record(score_file='./score.log'):
    all_record = {}
    if os.path.exists(score_file):
        with open(score_file, 'rb') as scoref:
            try:
                while True:
                    user = pickle.load(scoref)
                    all_record[user[0]] = user
            except EOFError:
                pass

    return all_record


# 输出历史成绩
def say_record(username, all_record):
    print('欢迎您，%s' % username)
    if len(all_record) > 0:
        if username in all_record:
            print(
                '''
游戏次数 : %d
最快猜出的轮数 ：%d
猜过的总轮数 ： %d
                '''
                % tuple(all_record[username][1:])
            )
            return all_record[username][1:]

    print('您还没有游戏记录...')
    return [0, 0, 0]


# 保存历史成绩
def save_record(all_record, score_file='./score.log'):
    with open(score_file, 'wb+') as score_handle:
        if len(all_record) > 0:
            for username in all_record:
                pickle.dump(all_record[username], score_handle)


# 游戏过程
def game():
    current_score = {
        'count': 0,
        'min': 0,
        'guess_count': 0
    }
    while True:
        num = random.randint(1, 50)
        current_score['count'] += 1
        print('请输入您的猜想:')
        for i in range(20):
            while True:
                try:
                    input_num = int(input())
                    if input_num < 1 or input_num > 50:
                        raise ValueError
                except ValueError:
                    print('请输入1-50之间的正整数')
                else:
                    break
            current_score['guess_count'] += 1
            if input_num < num:
                print('您猜的有点小了...')
            elif input_num == num:
                if current_score['min'] == 0 or current_score['min'] > i + 1:
                    current_score['min'] = i + 1
                print('恭喜您，猜对了...')
                break
            else:
                print('您猜的有点大了...')
            if i == 19:
                print('game over ...')

        continue_flag = input("要继续下一轮吗(y/n): \r\n")
        if continue_flag == 'n':
            current_score['min'] = 0 if current_score['min'] >= 20 else current_score['min']

            print(
                '''
本次游戏结果 ：
游戏次数 : %d
最快猜出的轮数 ：%d
猜过的总轮数 ： %d
                '''
                % (current_score['count'], current_score['min'], current_score['guess_count'])
            )
            return current_score


if __name__ == '__main__':
    say_hello()
    username = ''
    while True:
        username = input("请输入用户名(长度为5-10个字符):\n").strip()
        if 6 >= len(username) <= 10:
            break
        else:
            print('用户名长度不符...')
    all_record = read_record()

    # 输出历史成绩
    history_record = say_record(username=username, all_record=all_record)

    # 开始游戏
    print('\n游戏开始....\r\n')
    this_game = game()

    # 累计成绩
    history_record[0] += this_game['count']
    if this_game['min']:
        if history_record[1] == 0 or this_game['min'] < history_record[1]:
            history_record[1] = this_game['min']
    history_record[2] += this_game['guess_count']

    all_record[username] = [username] + history_record

    # 保存成绩
    save_record(all_record)
    print('bye~~~~~~~~')
